package es.us.lsi.daw.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import es.us.lsi.daw.servicios.MessageService;

/**
 * Servlet Filter implementation class SessionFilter
 */
public class LocaleFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		Assert.isInstanceOf(HttpServletRequest.class, request, "Can only process HttpServletRequest");
		Assert.isInstanceOf(HttpServletResponse.class, response, "Can only process HttpServletResponse");

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(httpRequest.getSession().getServletContext());
		MessageService mensaje = (MessageService) wc.getBean("mensaje");

		String cookieName = mensaje.obtenerMensaje("cookieName");
		String strCookieMaxAge = mensaje.obtenerMensaje("cookieMaxAge");
		int cookieMaxAge = 0;
		if (strCookieMaxAge != null) {
			cookieMaxAge = Integer.parseInt(strCookieMaxAge.trim());
		}

		String cookiePath = mensaje.obtenerMensaje("cookiePath");
		String paramLocaleName = mensaje.obtenerMensaje("paramLocaleName");
		String localeParam = httpRequest.getParameter(paramLocaleName);

		Locale locale = null;
		if (localeParam == null) {
			locale = new Locale("es_ES");
		} else {
			locale = new Locale(localeParam);
		}

		Cookie[] cookies = httpRequest.getCookies();
		int i = 0;
		if (cookies != null) {
			for (; i < cookies.length; i++) {
				if (cookies[i].getName().equals(cookieName)) {
					break;
				}
			}
		}

		if (cookies == null || i == cookies.length) {// la cookie no existe, la creo
			Cookie i18nCookie = new Cookie(cookieName, locale.getLanguage());
			i18nCookie.setPath(cookiePath);
			i18nCookie.setMaxAge(cookieMaxAge);
			httpResponse.addCookie(i18nCookie);
		} else if (localeParam != null) {
			cookies[i].setValue(locale.getLanguage());
			httpResponse.addCookie(cookies[i]);
		}

		// //Tratamiento de JSESSION_ID
		if (((HttpServletRequest) request).isRequestedSessionIdFromURL()) {
			String url = ((HttpServletRequest) request).getRequestURL().append(((HttpServletRequest) request).getQueryString() != null ? "?" + ((HttpServletRequest) request).getQueryString() : "")
					.toString();
			((HttpServletResponse) httpResponse).setHeader("Location", url);
			((HttpServletResponse) httpResponse).sendError(HttpServletResponse.SC_MOVED_PERMANENTLY);
			return;
		}

		// Prevent rendering of JSESSIONID in URLs for all outgoing links
		HttpServletResponseWrapper wrappedResponse = new HttpServletResponseWrapper((HttpServletResponse) httpResponse) {

			@Override
			public String encodeRedirectUrl(String url) {

				return url;
			}

			@Override
			public String encodeRedirectURL(String url) {

				return url;
			}

			@Override
			public String encodeUrl(String url) {

				return url;
			}

			@Override
			public String encodeURL(String url) {

				return url;
			}
		};

		chain.doFilter(request, wrappedResponse);
	}

	public void destroy() {

		// TODO Auto-generated method stub

	}

	public void init(FilterConfig arg0) throws ServletException {

		// TODO Auto-generated method stub

	}
}
